<?php
/*
 * $Id: annuaire_model.php 1083 2008-11-23 09:31:10Z hery $
 *
 *
 */
  

if (!defined('BASEPATH')) exit('No direct script access allowed');

class Album_model extends Model {
	var $fields = array
	(
		'album_tags' => array 
		(
		'id', 'tag', 'uri', 'aid'
		),
		'album_image_comments' => array
		(
		'id' , 'sid' , 'username', 'email', 'date', 'comment', 'notify'
		),
		'album_categories' => array 
		(
		'id', 'aid', 'title', 'description', 'date', 'username', 'email', 'view', 'valid', 'cover', 'g_id'
		),
		'album_images' => array 
		(
		'id', 'sid', 'aid', 'title', 'description', 'date', 'username', 'email', 'view', 'valid', 's', 't', 'm', 'o'
		),
		'album_infos' => array
		(
		'id', 'album', 'title', 'description', 'lang'
		)
	);


	function Album_model()
	{
		parent::Model();
		$this->get_settings();
	}

	
	
	function get_image($params = array())
	{
		$default_params = array
		(
			'order_by' => 'album_images.id DESC',
			'limit' => 20,
			'start' => null,
			'where' => array()
		);
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}

		$this->db->limit(1);

		if ($params['where'])
		{
			$this->db->where($params['where']);
		}
		$query = $this->db->get('album_images');

		if ($query->num_rows() == 0 )
		{
			return false;
		}
		else
		{
			$row = $query->row_array();
			
			
			$album = $this->get_album(array('where' => array('a.aid' => $row['aid'])));
			$row['g_id'] = $album['g_id'];
			$row['album_title'] = $album['title'];
			
			$this->db->select('sid, o');
			$this->db->where('album_images.aid', $row['aid']);
			$this->db->order_by($params['order_by']);
			
			$query = $this->db->get('album_images');
			
			
			if($family = $query->result_array())
			{
				$id = array_search(array('sid' => $row['sid'], 'o' => $row['o']), $family);
				if(($id - 1) >= 0) {
					// Ny mialoha
					$row['previous'] = $family[$id - 1];
				}
				if ( ( $id + 1 ) < count( $family ) ) {
					// Ny manaraka
					$row['next'] = $family[$id + 1];
				}
			}
			
			
			return $row;
			
		}
	}
	
	function get_images($params = array())
	{
		$hash = md5(serialize($params));
		$this->cache->remove_group('get_images');
		if (!$result = $this->cache->get('get_images' . $hash, 'album_image_list'))
		{
			$default_params = array
			(
				'order_by' => 'id DESC',
				'limit' => 20,
				'start' => null,
				'where' => array()
			);
			
			foreach ($default_params as $key => $value)
			{
				$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
			}
			
			
			$this->db->select('album_images.*, album_categories.g_id');
			$this->db->order_by($params['order_by']);
			$this->db->limit($params['limit'], $params['start']);
			$this->db->from('album_images');
			$this->db->join('album_categories', 'album_images.aid=album_categories.aid', 'left');
			
			if ($params['where'])
			{
				$this->db->where($params['where']);
			}
			
			
			$query = $this->db->get();
			
			

			if ($query->num_rows() == 0 )
			{
				$result = false;
			}
			else
			{
				$result = $query->result_array();
			}
			$this->cache->save('get_images' . $hash, $result, 'album_image_list', 0);
		}
		
		return $result;
		
	}

	function get_total_images($params)
	{
		$default_params = array
		(
			'order_by' => 'id DESC',
			'limit' => null,
			'start' => null,
			'where' => array()
		);
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
		$hash = md5(serialize($params));
		if (!$result = $this->cache->get('get_total_images' . $hash, 'album_image_list'))
		{
			$this->db->where($params['where']);
			$this->db->select('album_images.*, album_categories.g_id');
			$this->db->order_by($params['order_by']);
			$this->db->from('album_images');
			$this->db->join('album_categories', 'album_images.aid=album_categories.aid', 'left');
			$query = $this->db->get();
			
			$result = $query->num_rows();
			$this->cache->save('get_total_images' . $hash, $result, 'album_image_list', 0);
		}
		
		return $result;
	}
	
	function get_albums($params = array())
	{
		$default_params = array
		(
			'order_by' => 'id DESC',
			'limit' => null,
			'start' => null,
			'where' => array()
		);
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
		
		$hash = md5(serialize($params));
		if (!$result = $this->cache->get('get_albums' . $hash, 'album_list'))
		{
			//$this->db->select('a.*, i.s, i.m, i.t, i.o'); 
			$this->db->select('a.*'); 

			$this->db->from('album_categories a');
			//$this->db->join('album_images i', 'a.cover = i.sid', 'left');
			$this->db->order_by($params['order_by']);
			$this->db->limit($params['limit'], $params['start']);
			
			if ($params['where'])
			{
				$this->db->where($params['where']);
			}
			
			$query = $this->db->get();
			

			if ($query->num_rows() == 0 )
			{
				$result = false;
			}
			else
			{
				$rows = $query->result_array();
				$result = array();
				foreach($rows as $row)
				{
					$query = $this->db->get_where('album_infos', array('album' => $row['aid'], 'lang' => $this->session->userdata('lang')));
					if($info = $query->row_array())
					{
						if(isset($info['title'])) $row['title'] = $info['title'];
						if(isset($info['description'])) $row['description'] = $info['description'];
					}
					$result[] = $row;
				}
			}
			$this->cache->save('get_albums' . $hash, $result, 'album_list', 0);
		}
		
		return $result;
			
	}

	function get_album($params)
	{
		$default_params = array
		(
			'order_by' => 'a.id DESC',
			'limit' => 1,
			'start' => null,
			'where' => array(),
			'like' => array()
		);
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
		
		$this->db->select('a.*, i.s, i.m, i.t, i.o'); 
		$this->db->from('album_categories a');
		$this->db->join('album_images i', 'a.cover = i.sid', 'left');
		$this->db->order_by($params['order_by']);
		$this->db->limit($params['limit'], $params['start']);
		
		if ($params['where'])
		{
			$this->db->where($params['where']);
		}

		if ($params['like'])
		{
			$this->db->like($params['like']);
		}
		
		$query = $this->db->get();
		

		if ($query->num_rows() == 0 )
		{
			return false;
		}
		else
		{
			$row = $query->row_array();
			$this->db->where('aid', $row['aid']);
			$this->db->order_by('tag');
			$query = $this->db->get('album_tags');
			if ($query->num_rows() > 0)
			{
				$row['tags'] = $query->result_array();
			}
			
			$query = $this->db->get_where('album_infos', array('album' => $row['aid'], 'lang' => $this->session->userdata('lang')));
			if($info = $query->row_array())
			{
				if(isset($info['title'])) $row['title'] = $info['title'];
				if(isset($info['description'])) $row['description'] = $info['description'];
			}
			
			return $row;
		}
	}
	
	
	function get_total_albums($params)
	{
		$default_params = array
		(
			'order_by' => 'id DESC',
			'limit' => null,
			'start' => null,
			'where' => array()
		);
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
		$hash = md5(serialize($params));
		if(!$result = $this->cache->get('get_total_album_' . $hash, 'album_list'))
		{
			$query = $this->db->get_where('album_categories a', $params['where']);
			
			$result = $query->num_rows();
			$this->cache->save('get_total_album_' . $hash, $result, 'album_list', 0);
		}
		
		return $result;
	}

	function get_tags($params = array())
	{
		$default_params = array
		(
			'order_by' => 'tag',
			'limit' => null,
			'start' => null,
			'where' => array()
		);
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
		
		$this->db->where($params['where']);
		$this->db->limit($params['limit'], $params['start']);
		
		$this->db->select('count(tag) as cnt, album_tags.*');
		$this->db->group_by("tag");
		$this->db->order_by($params['order_by']);
		$query = $this->db->get("album_tags");
		if ($query->num_rows() == 0 )
		{
			return false;
		}
		else
		{
			return $query->result_array();
		}
		
	}

	function get_comment($params = array())
	{
		$default_params = array
		(
			'order_by' => 'album_image_comments.id',
			'limit' => null,
			'start' => null,
			'where' => array()
		);
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
		
		
		$this->db->from('album_image_comments');
		$this->db->where($params['where']);
		$this->db->limit($params['limit'], $params['start']);
		
		$this->db->order_by($params['order_by']);
		$query = $this->db->get();
		if ($query->num_rows() == 0 )
		{
			return false;
		}
		else
		{
			return $query->row_array();
		}
	
	}
	
	function delete_comment($params = array())
	{
		$default_params = array
		(
			'order_by' => 'album_image_comments.id',
			'limit' => 1,
			'start' => 0,
			'where' => array()
		);
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
		$this->db->where($params['where']);
		$this->db->limit($params['limit'], $params['start']);
		
		$this->db->order_by($params['order_by']);
		
		$this->db->delete('album_image_comments');
	}
	
	function get_comments($params = array())
	{
		$default_params = array
		(
			'order_by' => 'album_image_comments.id',
			'limit' => null,
			'start' => null,
			'where' => array()
		);
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
		
		
		$this->db->select('album_image_comments.*');
		$this->db->from('album_image_comments');
		$this->db->join('album_images', 'album_image_comments.sid = album_images.sid');
		$this->db->where($params['where']);
		$this->db->limit($params['limit'], $params['start']);
		
		$this->db->order_by($params['order_by']);
		$query = $this->db->get();
		if ($query->num_rows() == 0 )
		{
			return false;
		}
		else
		{
			return $query->result_array();
		}
		
	}
	
	function get_total_comments($params = array())
	{
		$default_params = array
		(
			'order_by' => 'album_image_comments.id DESC',
			'limit' => null,
			'start' => null,
			'where' => array()
		);
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
		
		
		$this->db->select('album_image_comments.id');
		$this->db->from('album_image_comments');
		$this->db->join('album_images', 'album_image_comments.sid = album_images.sid');
		$this->db->where($params['where']);
		
		$query = $this->db->get();
		return $query->num_rows();
		
	}
	
	function create_album($data)
	{
		$data['aid'] = uniqid('a');
		$data['date'] = mktime();
		if(!isset($data['username'])) $data['username'] = $this->user->username;
		if(!isset($data['email'])) $data['email'] = $this->user->email;
		
		$this->db->insert('album_categories', $data);
		$this->db->insert('album_infos', array(
			'album' => $data['aid'],
			'title' => $data['title'],
			'description' => $data['description'],
			'lang' => $this->session->userdata('lang')));
			
		$this->cache->remove_group('album_list');
				

		return $data['aid'];
	}
	
	function save_album()
	{
		$data = array();
		foreach ($this->fields['album_categories'] as $val)
		{
			
			if ($this->input->post($val) !== false)
			{
				$data[$val] = strip_tags( $this->input->post($val, TRUE) );
			}
		}
		
		
		if ($image_titles = $this->input->post('image_title'))
		{
			$image_descriptions = $this->input->post('image_description');
			foreach ($image_titles as $key => $val)
			{
				$idata['title'] = $this->db->escape($val);
				$idata['description'] = $this->db->escape($image_descriptions[$key]);
				$this->update_image($key, $idata);
			}
		}
		if ($image_delete = $this->input->post('image_delete'))
		{
			foreach($image_delete as $key => $val)
			{
				$this->delete_image($key);
			}
		}
		if ($data['aid'])
		{
			$this->db->where('aid', $data['aid']);
			$this->db->update('album_categories', $data);
			
			$this->db->where(array('album' => $data['aid'], 'lang' => $this->session->userdata('lang')));
			$this->db->update('album_infos', array(
				'title' => $data['title'],
				'description' => $data['description']));
				
			$this->cache->remove_group('album_list');
		}
		else
		{
			$data['aid'] = uniqid('a');
			$data['date'] = mktime();
			$data['username'] = $this->user->username;
			$data['email'] = $this->user->email;
			
			$this->db->insert('album_categories', $data);
			
			$this->db->insert('album_infos', array(
				'album' => $data['aid'],
				'title' => $data['title'],
				'description' => $data['description'],
				'lang' => $this->session->userdata('lang')));
				
			$this->cache->remove_group('album_list');
		}
		
		/*
		*saving tags
		*/
		if($this->input->post('aid'))
		{
			$this->db->delete('album_tags', array('aid' => $data['aid']));
		}
		
		$tags = array();
		if ($this->input->post('tags'))
		{
			$tags = $this->input->post('tags');
		}
		
		if($tag_str = $this->input->post('stag'))
		{
			$atags = explode(',', $tag_str);
			$tags = array_merge($tags, $atags);
		}	
		foreach($tags as $tag)
		{
			if($tag && trim($tag) != "")
			{
			$datatag = array('aid' => $data['aid'], 'tag' => trim($tag), 'uri' => format_title($tag));
			$this->db->insert('album_tags', $datatag);
			}
		}

		return $data['aid'];
	}

	function update_album($aid, $data)
	{
		
		$this->db->where('aid', $aid);
		if (is_array($data))
		{
			foreach ($data as $key => $val)
			{
				$this->db->set($key, $val, FALSE);
			}
			$this->db->update('album_categories');
			
			
			if(isset($data['title']) || isset($data['description']))
			{
				$this->db->where(array('album' => $aid, 'lang' => $this->session->userdata('lang')));
				$this->db->update('album_infos', array(
				'title' => $data['title'],
				'description' => $data['description']));
			}
			$this->cache->remove_group('album_list');

		}
		
	}

	function update_image($sid, $data)
	{
		
		$this->db->where('sid', $sid);
		if (is_array($data))
		{
			foreach ($data as $key => $val)
			{
				$this->db->set($key, $val, FALSE);
			}

			$this->db->update('album_images');
			//don't clear cache for image count
			if(!isset($data['view']))
			{
				$this->cache->remove_group('album_image_list');
			}
		}
		
	}
	
	function get_tadiavo($id)
	{
		if($content = $this->cache->get($id, 'tadiavo_cache'))
		{
			return $content;
		}
		else
		{
			return false;
		}
	}

	function save_tadiavo($tadiavo)
	{
		//cleaning
		$id = uniqid();
		$this->cache->save($id, $tadiavo, 'tadiavo_cache', 86400);
		return $id;
	}

	function get_album_by_tag($tag, $start = 0, $limit = 20)
	{
//		$this->db->select('vetso_tags.tag, vetso_poeta.poeta, vetso_vetso.*');
		$this->db->limit($limit, $start);
		$this->db->where(array('uri' => $tag));
		$query = $this->db->get('album_tags');

		if ($query->num_rows() >0)
		{
			$results = array();
			foreach ($query->result() as $row)
			{
				$results[] = $this->get_album(array('where' => array('a.aid' => $row->aid)));
			}
			return $results;
		}
		else
		{
			return false;
		}
		
	}
	
	function get_total_album_by_tag($tag)
	{
		$this->db->where('uri', $tag);
		$query = $this->db->get('album_tags');
		return $query->num_rows();
	}
	
	function save_comment()
	{
		$data = array();
		foreach ($this->fields['album_image_comments'] as $val)
		{
			if ($this->input->post($val) !== false)
			{
				$data[$val] = strip_tags( $this->input->post($val, TRUE) );
			}
		}
		
		$data['date'] = mktime();
		$data['username'] = $this->user->username;
		$data['email'] = $this->user->email;
		$this->db->insert('album_image_comments', $data);
		$id = $this->db->insert_id();
		
		return $id;
	}

	function get_users($params = array())
	{
		$default_params = array
		(
			'order_by' => 'cnt DESC',
			'limit' => null,
			'start' => null,
			'where' => array()
		);
		
		foreach ($default_params as $key => $value)
		{
			$params[$key] = (isset($params[$key]))? $params[$key]: $default_params[$key];
		}
		
		$hash = md5(serialize($params));
		if(!$result = $this->cache->get('get_users_' . $hash, 'album_list'))
		{
			$this->db->where($params['where']);
			$this->db->limit($params['limit'], $params['start']);
			
			$this->db->select('count(username) as cnt, username');
			$this->db->group_by("username");
			$this->db->order_by($params['order_by']);
			$query = $this->db->get("album_categories");
			if ($query->num_rows() == 0 )
			{
				$result = false;
			}
			else
			{
				$result = $query->result_array();
			}
			$this->cache->save('get_users_' . $hash, $result, 'album_list', 0);
		}
		return $result;
		
	}
	
	function delete($where)
	{
		if(!is_array($where)) $where = array('aid' => $where);
		$this->db->where($where);
		$this->db->delete('album_categories');
		
		if(isset($where['aid']))
		{
			$this->db->where('album' , $where['aid']);
			$this->db->delete('album_infos');
		}
		
		$this->cache->remove_group('album_list');
		return true;
	}
	
	function delete_image($where)
	{
		if(!is_array($where)) $where = array('sid' => $where);
		$this->db->where($where);
		$this->db->delete('album_images');
		$this->cache->remove_group('album_image_list');
		
		return true;
	}
	
	function save_image()
	{
		$data = array();
		foreach ($this->fields['album_images'] as $val)
		{
			
			if ($this->input->post($val) !== false)
			{
				$data[$val] = strip_tags( $this->input->post($val, TRUE) );
			}
		}
		
		// get file first
		if ($_FILES['image']['name'] != '')
		{

			//var_dump($this->input->post('image'));
			//there is an image attached
			$config['upload_path'] = './media/images/album/';
			$config['allowed_types'] = 'gif|jpg|png|GIF|JPG|PNG';
			
			//var_dump($config['upload_path']);
			$this->load->library('upload', $config);
		
			if ( ! $this->upload->do_upload('image'))
			{
				return false;
			}	
			else
			{
				$image_data = $this->upload->data();
				//hook for other treatment (watermark etc)
				$this->plugin->apply_filters('album_image_data', $image_data);
				
				if (isset($this->album_settings->storage))
				{
					$disk = $this->album_settings->storage;
					$this->load->library($disk);
					$result = $this->$disk->store($image_data);
					
					
					//$result = array ('s' => url, 'o' => etc...)
					if (!isset($result['s']) || !isset($result['t']) || !isset($result['m']) || !isset($result['o']))
					{
						//storage error
						return false;
					}
					
				}
			}
			$data['s'] = $result['s'];
			$data['m'] = $result['m'];
			$data['t'] = $result['t'];
			$data['o'] = $result['o'];
		}
		elseif(!$data['sid'])
		{
			return false;
			/*
			* todo
			* error message
			*/
		}
		

		if(!$data['title'])
		{
			$data['title'] = $image_data ['raw_name'];
		}
		
		if ($data['sid'])
		{
			$this->db->where('sid', $data['sid']);
			$this->db->update('album_images', $data);
		}
		else
		{
			$data['sid'] = uniqid('s');
			$data['date'] = mktime();
			$data['username'] = $this->user->username;
			$data['email'] = $this->user->email;
			
			$this->db->insert('album_images', $data);
		}
		
		$this->cache->remove_group('album_image_list');
		return $data['sid'];
	
	}
	
	function add_image($data)
	{
		//e.g. when importing
		if (is_array($data))
		{
			foreach ($data as $key => $val)
			{
				$this->db->set($key, $val);
			}
			$this->db->insert('album_images');
			$this->cache->remove_group('album_image_list');

		}
		
	}
	
	function get_settings()
	{
		if(!isset($this->album_settings))
		{
			$query = $this->db->get('album_settings');
			if ($query->num_rows() > 0)
			{
			   foreach ($query->result() as $row)
			   {
				  $this->album_settings->{$row->name} = $row->value;
			   }
			}			
		}

	}
	function set($name, $value)
	{	
		//update only if changed
		if (!isset($this->album_settings->$name)) {
			$this->album_settings->$name = $value;
			$this->db->insert('album_settings', array('name' => $name, 'value' => $value));
		}
		elseif ($this->album_settings->$name != $value) 
		{
			$this->album_settings->$name = $value;
			$this->db->update('album_settings', array('value' => $value), "name = '$name'");
		}
	}

	function move($direction, $id)
	{

		$query = $this->db->get_where('album_categories', array('id' => $id));
		
		/*
		if ($row = $query->row())
		{
			$parent_id = $row->parent_id;
			
		}
		else
		{
			$parent_id = 0;
		}
		*/
		
		$move = ($direction == 'up') ? -1 : 1;
		$this->db->where(array('id' => $id));
		
		$this->db->set('ordering', 'ordering+'.$move, FALSE);
		$this->db->update('album_categories');

		
		$this->db->where(array('id' => $id));
		$query = $this->db->get('album_categories');
		$row = $query->row();
		$new_ordering = $row->ordering;
		
		
		if ( $move > 0 )
		{
			$this->db->set('ordering', 'ordering-1', FALSE);
			$this->db->where(array('ordering <=' => $new_ordering, 'id <>' => $id)); //, 'parent_id' => $parent_id, 'lang' => $this->user->lang));
			$this->db->update('album_categories');
		}
		else
		{
			$this->db->set('ordering', 'ordering+1', FALSE);
			$where = array('ordering >=' => $new_ordering, 'id <>' => $id); //, 'parent_id' => $parent_id, 'lang' => $this->user->lang);
			
			$this->db->where($where);
			$this->db->update('album_categories');
		}
		//reordinate
		$i = 0;
		$this->db->order_by('ordering');
		$this->db->where(array('parent_id' => $parent_id)) ; //, 'lang' => $this->user->lang));
		
		$query = $this->db->get('album_categories');
		
		if ($rows = $query->result())
		{
			foreach ($rows as $row)
			{
				$this->db->set('ordering', $i);
				$this->db->where('id', $row->id);
				$this->db->update('album_categories');
				$i++;
			}
		}
		//clear cache
		$this->cache->remove_group('album_list');
		
	}

	
}
